package cn.audit.aop.interceptor;

import cn.audit.aop.myannotation.BussAnnotation;
import cn.audit.bean.pojo.OperationLog;
import cn.audit.bean.pojo.User;
import cn.audit.service.log.OperationLogService;
import cn.audit.utils.EmptyUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author: 李忆枫
 * @Date: ${date} ${time}
 */
@Aspect
@Component
public class LogInterceptor {

    @Resource
    private OperationLogService operationLogService;

    public LogInterceptor() {
        System.out.println("Aop");
    }

    @Pointcut("@annotation(cn.audit.aop.myannotation.BussAnnotation)")
    public void methodCachePointcut() {

    }

    @Around(value = "methodCachePointcut() && @annotation(annotation) && args(object,..)", argNames = "pj,annotation,object")
    public Object interceptorApplogic(ProceedingJoinPoint pj, BussAnnotation annotation, Object object) throws Throwable {
        System.out.println("moduleName:" + annotation.moduleName());
        System.out.println("option:" + annotation.option());
        object = pj.proceed();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        if (EmptyUtils.isNotEmpty(session.getAttribute("user"))) {
            User user = (User) session.getAttribute("user");
            OperationLog log = new OperationLog();
            //操作人
            log.setUserId(user.getId());
            //操作时间
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar ca = Calendar.getInstance();
            String operDate = df.format(ca.getTime());
            Date today = df.parse(operDate);
            log.setTime(today);
            //操作单位
            log.setUnits(user.getDepartment());
            //操作模块
            log.setModule(annotation.moduleName());
            //操作类型
            log.setType(annotation.type());
            //操作内容
            log.setContent(annotation.option());

            operationLogService.save(log);
        }
        return object;
    }

}
